package com.ext.aic.ui;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;

import com.ext.aic.R;
import com.ext.aic.apis.content.ContentDetailRequest;
import com.ext.aic.beans.Attachment;
import com.ext.aic.beans.FlowItem;
import com.ext.aic.beans.TagItem;
import com.ext.aic.beans.response.ContentDetailResponse;
import com.ext.aic.databinding.CopywritingDetailLayoutBinding;
import com.ext.aic.enums.ContentType;
import com.ext.aic.enums.EditNineSource;
import com.ext.aic.enums.EditType;
import com.ext.aic.fragment.NinePictureFragment;
import com.ext.aic.handler.FlowHandler;
import com.ext.aic.handler.ShareHandler;
import com.ext.aic.utils.FilteringUtils;
import com.ext.aic.utils.FragmentUtils;
import com.ext.aic.utils.RTEditUtils;
import com.ext.aic.utils.RedirectUtils;
import com.ext.aic.utils.ToastyUtils;
import com.ext.aic.utils.UserUtils;
import com.eyinfo.android_pure_utils.ObjectManager;
import com.eyinfo.android_pure_utils.utils.ObjectJudge;
import com.eyinfo.android_pure_utils.utils.PixelUtils;

import java.util.ArrayList;
import java.util.List;

public class CopywritingDetailActivity extends BaseActivity {

    private CopywritingDetailLayoutBinding binding;
    private String productId;
    private String creatorId;
    private ShareHandler shareHandler = new ShareHandler();
    private ContentDetailResponse detailResponse = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(this, R.layout.copywriting_detail_layout, null);
        binding = CopywritingDetailLayoutBinding.bind(view);
        setContentView(binding.getRoot());
        initParams();
        initView();
        RTEditUtils.getInstance().registerEditor(this, binding.contentRte);
        contentDetailRequest.request(this, this, productId);
    }

    private void initParams() {
        productId = getBundleString("productId");
        creatorId = getBundleString("creatorId");
    }

    private void initView() {
        binding.topView.backIv.setOnClickListener(v -> finish());
        binding.topView.titleTv.setText(R.string.copywriting_detail);
        binding.topView.shareIv.setOnClickListener(this::onShareClick);
        binding.topView.shareIv.setVisibility(View.VISIBLE);
        binding.editBtn.setOnClickListener(this::onEditClick);
        binding.refCreationBtn.setOnClickListener(this::onRefCreationClick);
        //仅自己文章才可以编辑
        String userId = UserUtils.getInstance().getUserId();
        if (!TextUtils.equals(userId, creatorId)) {
            binding.editBtn.setVisibility(View.GONE);
        } else {
            binding.editBtn.setVisibility(View.VISIBLE);
        }
    }

    public void onRefCreationClick(View v) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("detail", detailResponse);
        bundle.putString("creationType", EditType.referenceCreation.name());
        RedirectUtils.getInstance().startActivity(this, EditDetailActivity.class, bundle);
        finish();
    }

    public void onEditClick(View v) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("detail", detailResponse);
        bundle.putString("creationType", EditType.editing.name());
        RedirectUtils.getInstance().startActivity(this, EditDetailActivity.class, bundle);
        finish();
    }

    public void onShareClick(View v) {
        shareHandler.share(this);
    }

    private ContentDetailRequest contentDetailRequest = new ContentDetailRequest() {
        @Override
        protected void onContentDetailSuccess(ContentDetailResponse response) {
            detailResponse = response;
            binding.editBtn.setEnabled(true);
            binding.refCreationBtn.setEnabled(true);
            bindData();
        }
    };

    private void bindData() {
        if (detailResponse == null) {
            ToastyUtils.getInstance().show(getString(R.string.copywriting_detail_error));
            finish();
            return;
        }
        //九宫格
        int screenWidth = ObjectManager.getScreenWidth(this);
        int maxWidth = screenWidth - PixelUtils.dip2px(this, 24);
        List<Attachment> attachments = detailResponse.getAttachments();
        NinePictureFragment pictureFragment = new NinePictureFragment(maxWidth, false);
        pictureFragment.setAttachments(attachments);
        pictureFragment.setNineSource(EditNineSource.creation);
        FragmentUtils.getInstance().bind(getSupportFragmentManager(), R.id.copywriting_image_fl, pictureFragment);
        //标题
        binding.contentTitleTv.setText(detailResponse.getTitle());
        //文章内容
        ContentType contentType = detailResponse.getContentType();
        String html = FilteringUtils.getInstance().html(detailResponse.getBody());
//        binding.contentRte.setRichTextEditing(true, html);
        Editable editable = binding.contentRte.getText();
        editable.insert(0, html);
        binding.contentRte.setFocusable(false);
        binding.contentRte.setClickable(false);
        binding.contentRte.setLongClickable(false);
        //引用标签
        List<String> labels = detailResponse.getLabels();
        bindReferenceLabel(labels);
        //绑定推荐理由
        bindReason(detailResponse.getRecommendReason());
        //绑定标签
        bindTags(detailResponse.getTags());
    }

    private void bindTags(List<TagItem> tags) {
        if (ObjectJudge.isNullOrEmpty(tags)) {
            return;
        }
        binding.tagLl.setVisibility(View.VISIBLE);
        List<FlowItem> tabItems = new ArrayList<>();
        for (TagItem tag : tags) {
            tabItems.add(new FlowItem(tag.getName()));
        }
        FlowHandler flowHandler = new FlowHandler();
        flowHandler.bindTags(binding.tagFbl, tabItems);
    }

    private void bindReason(String recommendReason) {
        if (TextUtils.isEmpty(recommendReason)) {
            return;
        }
        binding.reasonLl.setVisibility(View.VISIBLE);
        binding.reasonTv.setText(recommendReason);
    }

    private void bindReferenceLabel(List<String> labels) {
        if (!ObjectJudge.isNullOrEmpty(labels)) {
            StringBuilder builder = new StringBuilder();
            for (String label : labels) {
                builder.append("#").append(label);
            }
            binding.referenceLabelTv.setVisibility(View.VISIBLE);
            binding.referenceLabelTv.setText(builder.toString());
        }
    }
}
